<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" v-show="showSearch" label-width="80px">
      <el-row>
        <el-col :span="4">
          <el-form-item label="报损单号" prop="wareReportingOdd">
            <el-input v-model="queryParams.wareReportingOdd" placeholder="请输入报损单号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="报损仓库" prop="wareId">
            <treeselect v-model="queryParams.wareId" :options="wareOptions" :normalizer="normalizer"
              placeholder="请选择" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="报损人" prop="wareReportingPersonId">
            <el-select filterable v-model="queryParams.wareReportingPersonId" placeholder="请选择">
              <el-option v-for="item in personOptions" :key="item.userId" :label="item.nickName"
                :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="报损状态" prop="approveStatus">
            <el-select v-model="queryParams.approveStatus" placeholder="请选择" clearable>
              <el-option key="0" label="待审批" :value="0" />
              <el-option key="1" label="已通过" :value="1" />
              <el-option key="2" label="被驳回" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="报损时间" prop="wareReportingTime">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="0px">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['erp:ErpWareReporting:add']">新增报损单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['erp:ErpWareReporting:export']">列表导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ErpWareReportingList" row-key="wareReportingId" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="50" align="center" :reserve-selection="true"/>
      <el-table-column label="报损单号" align="center" prop="wareReportingOdd" sortable/>
      <el-table-column label="报损仓库" align="center" prop="wareName" />
      <el-table-column label="报损状态" align="center" prop="approveStatus" sortable width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approveStatus == 0" type="info">待审批</el-tag>
          <el-tag v-if="scope.row.approveStatus == 1" type="success">已通过</el-tag>
          <el-tag v-if="scope.row.approveStatus == 2" type="danger">被驳回</el-tag>
          <el-tooltip placement="bottom" effect="light" v-if="scope.row.approveStatus == 2">
            <div slot="content">
              {{ scope.row.rejectReason }}
            </div>
            <i class="el-icon-warning-outline" style="margin-left: 5px; color: red;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="报损数量" align="center" prop="reportingNumber" sortable width="120"/>
      <el-table-column label="涉及金额" align="center" prop="priceSum" sortable width="180">
        <template slot-scope="scope">
          {{ formattedNumber(scope.row.priceSum) }}
        </template>
      </el-table-column>
      <el-table-column label="报损人" align="center" prop="wareReportingPersonName" width="120"/>
      <el-table-column label="联系电话" align="center" prop="phonenumber" />
      <el-table-column label="报损日期" align="center" prop="wareReportingTime" sortable width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wareReportingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交人" align="center" prop="createName" width="120"/>
      <el-table-column label="提交日期" align="center" prop="createTime" sortable width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="approveName" width="120" />
      <el-table-column label="审核日期" align="center" prop="approveTime" sortable width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createName" width="120"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.approveStatus == 2" size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['erp:ErpWareReporting:edit']">编辑</el-button>
          <el-button v-if="scope.row.approveStatus == 0" size="mini" type="text"
            @click="handleViewOrAudit(scope.row, 2)" v-hasPermi="['erp:ErpWareOverflow:audit']">审核</el-button>
          <el-button size="mini" type="text" @click="handleViewOrAudit(scope.row, 1)"
            v-hasPermi="['erp:ErpWareReporting:view']">详情</el-button>
            <el-button  size="mini" type="text" v-if="scope.row.approveStatus == 1"
            @click="handleViewOrAudit(scope.row,3)" v-hasPermi="['erp:ErpWareReporting:print']">打印</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['erp:ErpWareReporting:remove']">关闭</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 审核或预览报损单对话框 -->
    <el-dialog :title="viewAuditTitle" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" label-width="120px">
        <div id="printBSForm">
          <div class="title">
            湖南胜博清洁服务有限公司（报损单）
          </div>
          <div class="head-print">
            <div>报损单号：{{ form.wareReportingOdd }}</div>
            <div>报损仓库：{{ form.wareName }}</div>
            <div>报损人：{{ form.wareReportingPersonName }}</div>
            <div>报损日期：{{  parseTime(form.wareReportingTime, '{y}年{m}月{d}日')  }}</div>
          </div>
          <right-toolbar class="no-print" :search="false" :refresh="false" :columns="columns"></right-toolbar>
          <table class="table_print">
            <tr>
              <th v-if="columns[0].visible" width="80px">序号</th>
              <th v-if="columns[1].visible">商品编号</th>
              <th v-if="columns[2].visible">商品名称</th>
              <th v-if="columns[3].visible">商品类别</th>
              <th v-if="columns[4].visible">规格</th>
              <th v-if="columns[5].visible">单位</th>
              <th v-if="columns[6].visible">单位关系</th>
              <th v-if="columns[7].visible">当前库存</th>
              <th v-if="columns[8].visible">报损数量</th>
              <th v-if="columns[9].visible">商品单价</th>
              <th v-if="columns[10].visible">涉及金额</th>
            </tr>
            <tr v-for="(item,index) in form.detailsList" :key="index">
              <td v-if="columns[0].visible">{{index + 1}}</td>
              <td v-if="columns[1].visible">{{item.commodityNo}}</td>
              <td v-if="columns[2].visible">{{item.commodityName1}}</td>
              <td v-if="columns[3].visible">{{item.commodityType}}</td>
              <td v-if="columns[4].visible">{{item.commoditySpec}}</td>
              <td v-if="columns[5].visible">{{item.unitName1}}</td>
              <td v-if="columns[6].visible">{{item.unitRelationship}}</td>
              <td v-if="columns[7].visible">{{item.wareCommodityNumber}}</td>
              <td v-if="columns[8].visible">{{item.commodityNumber}}</td>
              <td v-if="columns[9].visible">{{formattedNumber(item.commodityPrice) }}</td>
              <td v-if="columns[10].visible">{{formattedNumber(item.commodityPrice * item.commodityNumber)}}</td>
            </tr>
          </table>
          <div class="head-print-2">
            <div>合计数量：{{ form.sumNumber }}</div>
            <div style="text-align: right; padding-right: 20px;">合计金额：{{ formattedNumber(form.sumMoney) }}</div>
          </div>
          <div class="single-line-print">制单人：{{ $store.getters.nickName}}</div>
          <div class="single-line-print">单据备注：{{ form.remark }}</div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="type == 2" @click="handleAuditOptions(1)">通过</el-button>
        <el-button type="primary" v-if="type == 2" @click="handleAuditOptions(2)">驳回</el-button>
        <el-button type="primary" v-print="'#printBSForm'" v-if="type == 3">打印</el-button>
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listErpWareReporting, getErpWareReporting, delErpWareReporting, auditErpWareReporting } from "@/api/erp/ErpWareReporting";
import { getSysUserList } from '@/api/system/user'
import { listErpWareHouse } from "@/api/erp/ErpWareHouse";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {formattedNumber} from "@/utils/ruoyi";

export default {
  name: "ErpWareReporting",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 多选ids
      ids: [],
      // 报损单表格数据
      ErpWareReportingList: [],
      // 是否显示弹出层
      open: false,
      viewAuditTitle: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wareReportingOdd: null,
        wareId: null,
        wareReportingPersonId: null,
        approveStatus: null,
      },
      // 仓库列表
      wareOptions: [],
      // 报损人列表
      personOptions: [],
      // 表单参数
      form: {
        attr: ''
      },
      // 日期选择
      dateRange: [],
       // 打印列
       columns: [
        { key: 0, label: `序号`, visible: true },
        { key: 1, label: `商品编号`, visible: true },
        { key: 2, label: `商品名称`, visible: true },
        { key: 3, label: `商品类别`, visible: true },
        { key: 4, label: `规格`, visible: true },
        { key: 5, label: `单位`, visible: true },
        { key: 6, label: `单位关系`, visible: true },
        { key: 7, label: `当前库存`, visible: true },
        { key: 8, label: `报损数量`, visible: true },
        { key: 9, label: `商品单价`, visible: true },
        { key: 10, label: `涉及金额`, visible: true }
      ]
    };
  },
  created() {
    this.handleGetListSysUser();
    this.getTreeselect();
    this.getList();
  },
  methods: {
    formattedNumber,
    /** 查询报损单列表 */
    getList() {
      this.loading = true;
      listErpWareReporting(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.ErpWareReportingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.wareReportingId)
    },
    // 获取用户列表
    handleGetListSysUser() {
      getSysUserList().then(res => {
        this.personOptions = res.data;
      })
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect() {
      listErpWareHouse().then(response => {
        this.wareOptions = this.handleTree(response.data, "wareId", "warePid");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        wareReportingId: null,
        wareReportingOdd: null,
        wareId: null,
        wareReportingPersonId: null,
        wareReportingTime: null,
        attr: null,
        remark: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveStatus: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/ErpWareReporting/add-addWareReporting/wareReporting/0");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push("/ErpWareReporting/add-addWareReporting/wareReporting/" + row.wareReportingId);
    },
    // 查看详情 / 审核
    handleViewOrAudit(row, type) {
      this.reset();
      getErpWareReporting(row.wareReportingId).then(res => {
        res.data.attr = !res.data.attr ? '' : res.data.attr;
        this.form = res.data;
        this.form.sumNumber = 0;
        this.form.sumMoney = 0;
        this.form.detailsList.forEach( i => {
          this.form.sumNumber += i.commodityNumber;
          this.form.sumMoney += i.commodityNumber * i.commodityPrice
        })
        this.viewAuditTitle = '报损单号：' + this.form.wareReportingOdd;
        this.type = type;
        this.open = true;
      })
    },
    handleAuditOptions(type) {
      this.form.approveStatus = type;
      if (type == 2) {
        this.$prompt('', '驳回原因', {
          center: true,
          inputType: 'textarea',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          this.form.rejectReason = value;
          this.handleAudit();
        })
      } else {
        this.handleAudit();
      }
    },
    // 审核
    handleAudit() {
      auditErpWareReporting({
        wareReportingId: this.form.wareReportingId,
        approveStatus: this.form.approveStatus,
        rejectReason: this.form.rejectReason
      }).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.open = false;
        this.getList();
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wareReportingIds = row.wareReportingId || this.ids;
      this.$modal.confirm('是否确认删除报损单编号为"' + wareReportingIds + '"的数据项？').then(function () {
        return delErpWareReporting(wareReportingIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/ErpWareReporting/export', {
        ...this.queryParams,
        exportIds: this.ids?.join(',')
      }, `报损单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
.title{
  padding: 10px;
  text-align: center;
  font-size: 32px;
  font-weight: 500;
}
.oddInfo{
  font-size: 16px;
}
.remark{
  padding-top: 10px;
  padding-bottom: 10px;
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
